// mela onlie 购物车界面 订制
import { PureComponent } from "react";
import { Button, Modal, Picker, List, InputItem, DatePicker } from "antd-mobile"
import { connect } from 'dva';
import { ActivityIndicator } from 'antd-mobile';
import { isNull, goToPage, handleImg } from '../../utils/helper';
import "./PlaceOrder.less"
import enUs from 'antd-mobile/lib/date-picker/locale/en_US';
import MToast from "../../components/Util/MToast";
import moment from 'moment';
import { routerRedux } from 'dva/router';
@connect(() => {
  return ({

  })
})
export default class PlaceOrder extends PureComponent {
  constructor(props) {
    super(props);
    this.timer = null;
    this.state = {
      loading: true,
      cartItems: [],
      order_type: -1,//收货方式 0 物流 1 自提
      cart_address: {
        // "recivier": "1",
        // "street": "2",
        // "city": "3",
        // "district": "4",
        // "country": "5",
        // "post_code": "6",
        // "concat": "7"
      },//地址对象
      have_address: false,//是否有地址
      date: "",//自提时间
      recivier: "",//联系人
      concat: "",//联系电话
      store_address: "",
      delivery_price:0,//物流运费
    }
  }
  componentWillMount() {
    let { dispatch, location } = this.props;
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: T("Fill in an order"),
        path: location.pathname + location.search
      }
    });
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/list",
          params: [

          ]
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            loading: false,
            cartItems: data.cart_items,
            store_address: data.store_address
          })
          this.changeAddress();
        }
      }
    });
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/row?_c=app_delivery_price_config",
          params: [

          ]
        },
        callback: (result) => {
          console.log(parseFloat(result.data.delivery_price));
          this.setState({
            delivery_price:parseFloat(result.data.delivery_price)
          })
        }
      }
    })
    return;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/row?_c=shop_info",
          params: [

          ]
        },
        callback: (result) => {

        }
      }
    })
  }
  componentDidMount() {

  }
  renderList() {
    let { cartItems } = this.state;
    if (!cartItems || cartItems.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T("No products")}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div style={{ borderTop: "10px solid #ddd" }}>
          <div style={{ padding: "5px 10px", fontSize: "16px", wordBreak: "break-all", lineHeight: 2 }} className="ellipsis1">
            {localStorage[MI_APP_CODE + "name"]}
          </div>
          <div>
            {
              cartItems.map((i, k) => {
                let { img_url, goods_name, price, quantity, item_id } = i;
                return (
                  <div key={k} data-flex="cross:center box:first" style={{ padding: "10px", borderBottom: "1px solid #ddd" }}>
                    <div data-flex="cross:center">
                      <img src={handleImg(img_url)} alt="" style={{ width: "40px", marginRight: "10px" }} />
                    </div>
                    <div>
                      <div className="ellipsis2">
                        {goods_name}
                      </div>
                      <div style={{ color: "red", marginTop: "10px" }}>
                        € {price} x {quantity}
                      </div>
                    </div>
                  </div>
                )
              })
            }
          </div>
        </div>
      )
    }
  }
  confirmOrder() {

    let { dispatch } = this.props;
    let { cart_address, cartItems, order_type, date, recivier, concat, leaveMessage,delivery_price } = this.state;
    if (order_type == -1) {
      MToast.fail(T("Please select way"), 1.5, null, false);
      return;
    }
    else if (order_type == 0) {//物流配送
      if (Object.keys(cart_address).length == 0) {
        MToast.fail(T("Enter shipping address"), 1.5, null, false);
        return;
      }
    }
    else {//自提
      if (isNull(date)) {
        MToast.fail(T("Please select a pick up time"), 1.5, null, false);
        return;
      }
      if (isNull(recivier)) {
        MToast.fail(T("Please enter a contact name"), 1.5, null, false);
        return;
      }
      if (isNull(concat)) {
        MToast.fail(T("Enter mobile number"), 1.5, null, false);
        return;
      }
    }
    let pay_amount = 0;
    let freight_amount = order_type == 0 ? delivery_price : 0;
    cartItems.map(i => {
      pay_amount += i.price * i.quantity
    })
    let total_amount = pay_amount + freight_amount;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "order/generateConfirmOrder",
          params: [

          ]
        },
        isEditCreate: true,
        data: {
          items: cartItems,
          order_type: order_type,
          total_amount: total_amount,
          pay_amount: pay_amount,
          freight_amount: freight_amount,

          street: order_type == 0 ? cart_address.street : "",
          city: order_type == 0 ? cart_address.city : "",
          country: order_type == 0 ? cart_address.country : "",
          district: order_type == 0 ? cart_address.district : "",
          post_code: order_type == 0 ? cart_address.post_code : "",

          recivier: order_type == 0 ? cart_address.recivier : recivier,
          concat: order_type == 0 ? cart_address.concat : concat,
          pick_up_time: order_type == 0 ? null : moment(date).valueOf(),

          note: leaveMessage
        },
        callback: (result) => {
          MToast.info(T("Sccessfully ordered"));
          setTimeout(() => {
            if (browser.isInApp) {
              Func.callHander(bridge, "openHomePage", {})
            }
            else{
              this.props.history.replace("/");
              window.location.reload();
            }
          }, 500);

        }
      }
    })
    // 确认下单 成功之后提示下单成功 然后返回首页
    // goToPage({ dispatch, config: { url: "/page?_c=mela_shop_home" }, })
  }
  // 填写地址页面返回时触发
  changeAddress = () => {
    let cart_address = localStorage.getItem(MI_APP_CODE + "cart_address");
    console.log("cart_address:" + cart_address);
    if (!isNull(cart_address)) {
      // localStorage.removeItem(MI_APP_CODE + "cart_address");
      this.setState({
        cart_address: JSON.parse(cart_address),
        have_address: true,
        order_type:0
      })
    }
  }
  render() {
    let { dispatch } = this.props;
    let { loading, cartItems, order_type, have_address, cart_address, store_address,delivery_price } = this.state;
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    let totalPrice = 0;
    let total = 0;
    cartItems.map(i => {
      totalPrice += i.price * i.quantity
    })
    if (order_type == 0) {
      total = totalPrice + delivery_price
    }
    else {
      total = totalPrice
    }
    let order_type_value = []
    if (isNull(order_type)) {
      order_type_value = []
    }
    else {
      order_type_value = [order_type * 1]
    }
    return (
      <div className="normal placeOrder" style={{ background: "#fff" }}>
        <div style={{ fontSize: "14px" }}>

          <div style={{ padding: "3px 10px", background: "#fff" }} className="mrequired">
            <Picker
              data={[
                {
                  label: T("Express delivery"),
                  value: 0
                },
                {
                  label: T("Pick up by yourself"),
                  value: 1
                }
              ]}
              cols={1}
              title={T("Way")}
              // cascade={false}
              extra={T("Please select")}
              value={order_type_value}
              onChange={v => this.setState({ order_type: v.join("") })}
              onOk={v => this.setState({ order_type: v.join("") })}
              okText={T("Ok")}
              dismissText={T("Cancel")}
            >
              <List.Item arrow="horizontal"> {T("Way")}：</List.Item>
            </Picker>
          </div>

          {
            order_type == 0 && <div key={0} data-flex={"box:first" + (have_address ? '' : ' cross:center')} style={{ padding: "10px", paddingLeft: "25px", minHeight: "44px", border: "1px solid #ddd", borderLeft: 0, borderRight: 0 }}>
              <div style={{ marginRight: "10px" }} className="required">
                {T("Shipping address")}：
              </div>
              {
                have_address ?
                  <div data-flex="box:last" style={{ color: "#999" }}>
                    <div>
                      <div>
                        {cart_address.country} {cart_address.district} {cart_address.city} {cart_address.street}
                      </div>
                      <div>
                        {cart_address.recivier}
                      </div>
                      <div>
                        {cart_address.concat}
                      </div>
                      <div>
                        {cart_address.post_code}
                      </div>
                    </div>
                    <div onClick={() => {
                      if (browser.isInApp) {
                        Func.registerHanderBridge("callbackCloseWindow", this.changeAddress);
                      }
                      localStorage.setItem(MI_APP_CODE + "old_cart_address", JSON.stringify(cart_address))
                      goToPage({ dispatch, config: { url: "/addAddress" }, isReplace: false })
                    }}>
                      <img style={{ width: "30px" }} src="image/cart_edit.png" alt="" srcset="" />
                    </div>
                  </div> :
                  <div style={{ color: "#999" }} onClick={() => {
                    if (browser.isInApp) {
                      Func.registerHanderBridge("callbackCloseWindow", this.changeAddress);
                    }
                    goToPage({ dispatch, config: { url: "/addAddress" }, isReplace: false })
                  }}>
                    {T("Enter shipping address")}
                  </div>
              }
            </div>
          }
          {
            order_type == 0 && <div key={1} data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px" }}>
              <div style={{ marginRight: "10px" }}>
                {T("Delivery time")}：
                </div>
              <div style={{ color: "#999" }}>
                {T("Estimated delivery within 7 days")}
              </div>
            </div>
          }
          {
            order_type == 1 && <div data-flex="box:first" style={{ padding: "10px", paddingTop: "14px", paddingLeft: "25px", minHeight: "44px", borderTop: "1px solid #ddd" }}>
              <div style={{ marginRight: "10px" }}>
                {T("Store address")}：
              </div>
              <div style={{ color: "#999", textAlign: "left" }}>
                {store_address}
              </div>
            </div>
          }
          {
            order_type == 1 && <div style={{ padding: "3px 10px", borderTop: "1px solid #ddd" }} className="mrequired">
              <DatePicker
                locale={enUs}
                mode="date"
                title={T("Pick up time")}
                extra={T("Please select")}
                value={this.state.date}
                onChange={date => this.setState({ date })}
                okText={T("Ok")}
                dismissText={T("Cancel")}
              >
                <List.Item arrow="horizontal">{T("Pick up time")}:</List.Item>
              </DatePicker>
            </div>
          }
          {
            order_type == 1 && <div style={{ padding: "3px 10px", borderTop: "1px solid #ddd" }} className="mrequired">
              <InputItem
                labelNumber={8}
                clear
                onChange={(e) => {
                  this.setState({
                    recivier: e
                  })
                }}
                placeholder={T("Please enter a contact name")}
              >{T("Contact person")}:</InputItem>
            </div>
          }
          {
            order_type == 1 && <div style={{ padding: "3px 10px", borderTop: "1px solid #ddd" }} className="mrequired">
              <InputItem
                labelNumber={8}
                clear
                onChange={(e) => {
                  this.setState({
                    concat: e
                  })
                }}
                placeholder={T("Enter mobile number")}
              >{T("Tel")}:</InputItem>
            </div>
          }
        </div>
        <div style={{ borderBottom: "10px solid #ddd" }}>
          {this.renderList()}
          <div style={{ padding: "3px 10px" }}>
            <InputItem
              labelNumber={8}
              clear
              onChange={(e) => {
                this.setState({
                  leaveMessage: e
                })
              }}
              placeholder={T("Please enter leave message")}
            >{T("Leave message")}:</InputItem>
          </div>
        </div>
        <div>
          <div data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px", borderBottom: "1px solid #ddd" }}>
            <div style={{ marginRight: "10px" }}>
              {T("Delivery time")}：
            </div>
            <div style={{ color: "#000", textAlign: "right" }}>
              € {totalPrice.toFixed(2)}
            </div>
          </div>
          <div data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px" }}>
            <div style={{ marginRight: "10px" }}>
              {T("Shipping")}：
            </div>
            <div style={{ color: "#000", textAlign: "right", color: "red" }}>

              {
                order_type == 0 ? delivery_price.toFixed(2) : "+ € 0.00"
              }

            </div>
          </div>
        </div>
        {
          cartItems.length > 0 &&
          <div style={{ height: "50px", position: "fixed", bottom: 0, width: "100%", borderTop: "1px solid #ddd", background: "#fff", padding: "0 10px" }} data-flex="cross:center main:justify">
            <div style={{ fontSize: "16px" }}>
              {T("Total")}: <span style={{ color: "red" }}>€
              {total.toFixed(2)}
              </span>
            </div>
            <Button size="small" type="primary" style={{ padding: "0 10px", height: "40px", lineHeight: "40px", fontSize: "18px" }} onClick={() => { this.confirmOrder() }}>{T("Confirm order")}</Button>
          </div>
        }
      </div >
    )
  }
}
